package com.doudou.pay.helper.commons;

import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by zhang on 2016/3/28.
 */
public class DateTimeTool {
    /**
     * 获取当前系统时间
     * @return 返回时间类型 yyyy-MM-dd HH:mm:ss
     */
    public static Date getNowDate(){
        Date currentTime = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = sdf.format(currentTime);
        ParsePosition pos = new ParsePosition(0);
        Date currentTime_2 = sdf.parse(dateString,pos);
        return currentTime_2;
    }

    public static Date getDate(String dateformat) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(dateformat);
        return date;
    }

    /**
     * Date类型格式化转换成String类型
     * @param pattern
     * @param date
     * @return
     */
    public static String dateFormat(String pattern,Date date){
        if(date == null){
            return "";
        }
        if(pattern ==null || pattern.equals("")) {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
        }else{
            return new SimpleDateFormat(pattern).format(date);
        }
    }

    /**
     * String类型按格式转化成Date类型
     *
     * @version 2011-8-31 上午10:54:47
     * @param pattern
     * @param date
     * @return
     */
    public static Date dateFormat(String pattern, String date) {
        if (!StringUtils.hasText(date)) {
            return null;
        }
        try {
            if (pattern == null || pattern.equals("")) {
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
            }
            else {
                return new SimpleDateFormat(pattern).parse(date);
            }
        }
        catch (ParseException e) {
            e.printStackTrace();
        }
        return new Date();
    }
}
